package com.xinziruo.richclient;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import com.xinziruo.richclient.handler.ClientCommandProtocolHandlerForMysqlDB;
import com.xinziruo.richclient.handler.ClientCommandProtocolHandlerForSolr;
import com.xinziruo.richclient.support.CommandClientBroker;
import com.xinziruo.richclient.support.command.impl.OnlineCommand;

public class App {

	private CommandClientBroker commandClientBroker;
	private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {

		@SuppressWarnings("static-access")
		Option hostOpt = OptionBuilder.withArgName("host")
										.hasArg()
										.withDescription("server'ip or domain")
										.isRequired(true)
										.create("h");

		@SuppressWarnings("static-access")
		Option portOpt = OptionBuilder.withArgName("port")
										.hasArg()
										.withDescription("the port that server listening")
										.isRequired(true)
										.create("p");

		Options options = new Options().addOption(hostOpt).addOption(portOpt);

		HelpFormatter formatter = new HelpFormatter();
		CommandLineParser parser = new GnuParser();
		try {

			CommandLine line = parser.parse(options, args);
			String host = line.getOptionValue("h");
			int port = Integer.parseInt(line.getOptionValue("p"));

			App app = new App();
			if(port == 8333){
				app.commandClientBroker = new CommandClientBroker(host, port, new ClientCommandProtocolHandlerForSolr());
				System.out.println("connect to server success,waiting for server's command... insert to solr");
			}
			else if(port == 8334){
				app.commandClientBroker = new CommandClientBroker(host, port, new ClientCommandProtocolHandlerForMysqlDB());
				System.out.println("connect to server success,waiting for server's command... insert to mysqlDB");
			}		
			app.shareOnlineStatus();
		} catch (ParseException e) {
			formatter.printHelp("crawl", options);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			System.exit(0);
		}
	}

	protected void shareOnlineStatus() {
		executor.scheduleAtFixedRate(new Runnable() {

			public void run() {
				commandClientBroker.writeCommand(new OnlineCommand());
			}
		}, 10, 60, TimeUnit.SECONDS);
	}
}
